<template>
  <div class="home">
    <div class="exam-header">
      <div class="title-wrapper">
        <div class="title-section">
          <h1 class="exam-title">实有人口考试</h1>
          <div class="timer-section">
            <i class="el-icon-time"></i>
            <span class="timer-label">剩余时间:</span>
            <span class="timer-value" :class="{'warning': isTimeWarning}">{{ min }}:{{ sec }}</span>
            <span class="timer-value">请输入人像对应的姓氏，例如：“刘莉”，输入“刘”即可。</span>
          </div>
        </div>
        <div class="action-section">
          <el-button 
            type="primary" 
            size="medium"
            icon="el-icon-finished"
            round
            @click="handHandPopExam"
          >
            提交
          </el-button>
        </div>
      </div>
    </div>
    <div class="nav">
      <el-divider direction="vertical"></el-divider>
      <LeftAvarto
        :imageData="this.allQu"
        :popQuList="this.allItem"
        @save="this.save"
        @onState="onState"
        @onSubmit="onSubmit"
      ></LeftAvarto>
      <!-- <el-divider direction="vertical"></el-divider>
      <RightAvarto
        :popQuData="this.popQuData"
        :isState="this.isState"
        :cardItem = "this.cardItem"
        @onSubmit="onSubmit"
        @onState="onState"
      ></RightAvarto> -->
    </div>
  </div>
</template>
<script>
import LeftAvarto from "./components/LeftAvarto.vue";
import RightAvarto from "./components/RightAvarto.vue";
import { paperPopDetail, popQuDetail,handPopExam,fillPopAnswer } from "@/api/paper/exam";
import { Loading } from "element-ui";

export default {
  name: "PopulationExam",
  components: {
    LeftAvarto,
    RightAvarto,
  },

  created() {
    const id = this.$route.params.id;
    if (typeof id !== "undefined") {
      this.paperId = id;
      this.fetchData(id);
    }
  },

  data() {
    return {
      selected: "1",
      isState: false,
      isItem: {
        id: 1,
        type: "1",
        delivery: true,
        image: "./image/wj.png",
        name: "吴京",
        sex: "男",
        occupation: ["演员"],
        nativePlace: "中国",
        detial: "中国演员1",
      },
      isIndex: 0,
      isdisabled: true,

      //试卷详情
      paperData: {
        popQuList: [],
      },
      //所有题目信息
      allItem: [],
      //所有题目
      allQu: [],
      // 当前题目
      cardItem: {},
      popQuData: {},
      // 倒计时相关
      min: '00',
      sec: '00',
      timer: null,
      isTimeWarning: false
    };
  },
  methods: {
    save(item) {
      // this.fetchQuData(item);
      // this.handSave(item)
      this.cardItem = item
    },
    onState(item) {
      console.log(item);
      this.isState = item;
    },
    
    onSubmit(item){
      // console.log(item);
      const params = { paperId: this.paperId, quId: this.cardItem.quId, name: item.name, job: item.job, address:item.address, content:item.content }
      this.handSave(params)
    },

     /**
     * 统计有多少题没答的
     * @returns {number}
     */
     countNotAnswered() {
      let notAnswered = 0

      return notAnswered
    },
    // 试卷详情
    fetchData(id) {
      const params = { id: id };
      paperPopDetail(params).then((response) => {
        // 试卷内容
        this.paperData = response.data;
        console.log("----->", response.data);
        // 获得第一题内容
        if (this.paperData.popQuList) {
          this.cardItem = this.paperData.popQuList[0];
        }

        const that = this;

        this.paperData.popQuList.forEach((item) => {
          this.allItem.push(item);
        });

        this.paperData.popQu.forEach((item) => {
          item.name = ""
          this.allQu.push(item);
        });

        // 顺序重构
        that.allItem.forEach((k, v) => {
          k.sort = v;
        });
        //
        this.cardItem = that.allItem[0];
        // 当前选定
        this.fetchQuData(this.cardItem);

        // 倒计时
        this.countdown();
      });
    },

    // 保存答案
    handSave(item, callback) {
      
      
      const params = { paperId: this.paperId, quId: this.cardItem.quId, name: item.name, job: item.job, address:item.address, content:item.content }
      fillPopAnswer(params).then(() => {
        // 必须选择一个值
        // if (answers.length > 0 || this.saqValue != '') {
        //   // 加入已答列表
        //   this.cardItem.answered = true
        // }
        if(item.name != ''){
          this.cardItem.answered = true
        }

        // 最后一个动作，交卷
        if (callback) {
          callback()
        }

        // 查找详情
        this.fetchQuData(item)
      })
    },

    // 试卷详情
    fetchQuData(item) {
      // 打开
      const loading = Loading.service({
        text: "拼命加载中",
        background: "rgba(0, 0, 0, 0.7)",
      });

      // 获得详情
      this.cardItem = item;

      // 查找下个详情
      const params = { paperId: this.paperId, quId: item.quId };
      popQuDetail(params).then((response) => {
        console.log(response, "----+>");
        this.popQuData = response.data;
        loading.close();
      });
    },

    doHandler() {
      this.handleText = '正在提交答案，请等待...'
      this.loading = true

      const params = { id: this.paperId }
      handPopExam(params).then(() => {
        this.$message({
          message: '答案提交成功，即将进入下一个项目！',
          type: 'success'
        })

        // this.$router.push({ name: 'ShowPopExam', params: { id: this.paperId } })
        setTimeout(()=>{
          this.$router.push({name:"SafetyExam"})
        },1000)
      })
    },

    // 交卷操作
    handHandPopExam() {
      const that = this

      // 交卷保存答案
      this.handSave(this.cardItem, function () {
        const notAnswered = that.countNotAnswered()

        let msg = '确认要提交吗？'

        if (notAnswered > 0) {
          msg = '您还有' + notAnswered + '题未作答，确认要提交吗?'
        }

        that.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.doHandler()
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '提交答案已取消，您可以继续作答！'
          })
        })
      })
    },


    // 倒计时
    countdown() {
      if(this.timer) {
        clearTimeout(this.timer);
      }
      
      const leftSeconds = this.paperData.leftSeconds;

      // 强制交卷
      if (leftSeconds <= 0) {
        this.doHandler();
        return;
      }

      // 时间少于5分钟显示警告
      if(leftSeconds <= 300) {
        this.isTimeWarning = true;
      }

      // 时
      const min = parseInt((leftSeconds / 60) % 60);
      const sec = parseInt(leftSeconds % 60);

      this.min = min > 9 ? min : "0" + min;
      this.sec = sec > 9 ? sec : "0" + sec;
      
      this.paperData.leftSeconds -= 1;
      
      this.timer = setTimeout(() => {
        this.countdown();
      }, 1000);
    },
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if(this.timer) {
      clearTimeout(this.timer);
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100vh;
  // background-image: url("/images/bg/bg_12_16.jpg");

  .exam-header {
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    
    .title-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 15px 30px;
      
      .title-section {
        display: flex;
        align-items: center;
        gap: 30px;

        .exam-title {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin: 0;
        }

        .timer-section {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .el-icon-time {
            font-size: 22px;
            color: #409EFF;
          }

          .timer-label {
            font-size: 22px;
            color: #606266;
          }

          .timer-value {
            font-size: 22px;
            font-weight: bold;
            color: #ec3a3a;
            min-width: 60px;
            text-align: center;
            margin-left: 20px;
            
            &.warning {
              color: #F56C6C;
              animation: blink 1s infinite;
            }
          }
        }
      }

      .action-section {

        position: absolute;
        right: 15px;

        .el-button {
          padding: 12px 25px;
          font-size: 16px;
        }
      }
    }
  }

  .nav {
    width: 100%;
    height: calc(100% - 80px);
    display: flex;

    .el-divider {
      height: 100%;
    }
  }
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
